package com.yeziji.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 响应工具类
 *
 * @author gzkemays
 * @since 2021/12/21 16:59
 */
public class ResponseUtils {
    /**
     * 写出 json
     *
     * @param response 响应
     * @param data     写出数据
     */
    public static void writeJson(HttpServletResponse response, Object data) {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write((new ObjectMapper()).writeValueAsString(data));
        } catch (IOException var8) {
            var8.printStackTrace();
        } finally {
            if (Objects.nonNull(out)) {
                out.flush();
                out.close();
            }
        }
    }

    public static <T> void writePojo(HttpServletResponse response, T data) {
        Class<?> clazz = data.getClass();
        Field[] fields = clazz.getDeclaredFields();
        JSONObject json = new JSONObject();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object o = field.get(data);
                if (o != null) {
                    json.put(field.getName(), o);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        writeJson(response, json);
    }
}
